package com.zmovie.admin.controller.hall;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmovie.admin.constant.Constants;
import com.zmovie.admin.controller.vo.HallVO;
import com.zmovie.common.error.BusinessException;
import com.zmovie.common.error.EnumBusinessError;
import com.zmovie.common.response.CommonReturnType;
import com.zmovie.framework.domain.Cinema;
import com.zmovie.framework.domain.Hall;
import com.zmovie.framework.domain.HallType;
import com.zmovie.framework.service.CinemaService;
import com.zmovie.framework.service.HallService;
import com.zmovie.framework.service.HallTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 电影厅管理模块
 * @since 2023-12-02 17:02
 */
@Controller
@RequestMapping("/hall/info")
@Api(tags = "电影厅管理模块")
public class HallInfoController {
    @Autowired
    private HallService hallService;
    @Autowired
    private CinemaService cinemaService;
    @Autowired
    private HallTypeService hallTypeService;

    @GetMapping
    @ApiOperation("影厅管理页面")
    public String index(Model model) {
        //分页查询
        Page<Hall> hallPage = hallService.pageHall(Integer.valueOf(Constants.PAGE_NO), Integer.valueOf(Constants.PAGE_SIZE), new Hall());
        model.addAttribute(Constants.HALL_PAGE_KEY, convert(hallPage));
        //影院列表
        List<Cinema> cinemas = cinemaService.list();
        model.addAttribute(Constants.CINEMAS_KEY, cinemas);
        //分类列表
        List<HallType> hallTypes = hallTypeService.listHallType(new HallType());
        model.addAttribute(Constants.HALL_TYPES_KEY, hallTypes);
        return "hall/hall_info";
    }
    @GetMapping("/{id}")
    @ApiOperation("根据id获取影厅信息")
    @ResponseBody
    public Object getHall(@PathVariable("id") Integer id){
        return CommonReturnType.success(hallService.getById(id));
    }

    @PostMapping
    @ApiOperation("添加影厅")
    @ResponseBody
    public Object addHall(@Validated Hall hall){
        //设置总座位数
        hall.setSeatNums(hall.getRowNums() * hall.getSeatNumsRow());
        //设置座位状态(0表示可用)
        int[][] seatState = new int[hall.getRowNums()][hall.getSeatNumsRow()];
        //序列化
        String jsonStr = JSON.toJSONString(seatState);
        //反 List<int[]> seatState = JSON.parseArray(jsonStr, int[].class);
        hall.setSeatState(jsonStr);
        hallService.save(hall);
        return CommonReturnType.success("添加成功!");
    }

    @PutMapping
    @ApiOperation("修改影厅")
    @ResponseBody
    public Object updateHall(@Validated Hall hall) throws BusinessException {
        if(hall.getId() == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        //总座位数
        hall.setSeatNums(hall.getRowNums() * hall.getSeatNumsRow());
        //设置座位状态(0表示可用)
        int[][] seatState = new int[hall.getRowNums()][hall.getSeatNumsRow()];
        //序列化
        String jsonStr = JSON.toJSONString(seatState);
        //反 List<int[]> seatState = JSON.parseArray(jsonStr, int[].class);
        hall.setSeatState(jsonStr);
        hallService.updateById(hall);
        return CommonReturnType.success("修改成功!");
    }

    @PutMapping("/state")
    @ApiOperation("修改影厅状态")
    @ResponseBody
    public Object updateHallState(Hall hall) throws BusinessException {
        //参数校验
        if(hall.getId() == null || hall.getHallState() == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        boolean update = hallService.updateHallState(hall);
        if(!update){
            throw new BusinessException(EnumBusinessError.OPERATOR_ERROR);
        }
        return CommonReturnType.success("修改状态成功!");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除影厅")
    @ResponseBody
    public Object deleteHall(@PathVariable("id")Integer id){
        hallService.removeById(id);
        return CommonReturnType.success("删除成功!");
    }

    @DeleteMapping
    @ApiOperation("批量删除影厅")
    @ResponseBody
    public Object deleteHallBatch(Integer[] id) throws BusinessException {
        if(id == null || id.length == 0){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        hallService.removeByIds(Arrays.asList(id));
        return CommonReturnType.success("批量删除成功!");
    }

    @PostMapping("/search")
    @ApiOperation("搜索")
    public String search(Hall hall, Model model, Integer pageNo, Integer pageSize){
        Page<Hall> hallPage = hallService.pageHall(pageNo, pageSize, hall);
        model.addAttribute(Constants.HALL_PAGE_KEY, convert(hallPage));
        return "hall/hall_info :: hallList";
    }

    @PostMapping("/seat")
    public String seat(Model model, Integer id) throws BusinessException {
        //参数校验
        if(id == null){
            throw new BusinessException(EnumBusinessError.PARAMETER_VALIDATION_ERROR);
        }
        Hall hall = hallService.getById(id);
        List<int[]> seat = JSON.parseArray(hall.getSeatState(), int[].class);
        //座位信息
        model.addAttribute("row", seat.size());
        model.addAttribute("col", seat.get(0).length);
        model.addAttribute("hallId", id);
        model.addAttribute(Constants.SEAT_KEY, seat);
        return "hall/hall_info :: seatData";
    }
    @PutMapping("/saveSeat")
    @ApiOperation("保存座位")
    @ResponseBody
    public Object saveSeat(Hall hall) throws BusinessException {
        boolean success = hallService.updateHallSeat(hall);
        if(!success){
            throw new BusinessException(EnumBusinessError.OPERATOR_ERROR);
        }
        return CommonReturnType.success("保存成功!");
    }
    private HallVO convert(Hall hall){
        HallVO hallVO = new HallVO();
        BeanUtils.copyProperties(hall, hallVO);
        //所属影院
        Cinema cinema = cinemaService.getById(hall.getCinemaId());
        hallVO.setCinema(cinema);
        //影厅类型
        HallType hallType = hallTypeService.getById(hall.getHallTypeId());
        hallVO.setHallType(hallType);
        return hallVO;
    }
    private Page<HallVO> convert(Page<Hall> hallPage){
        Page<HallVO> hallVOPage = new Page<>();
        BeanUtils.copyProperties(hallPage, hallVOPage);
        List<HallVO> hallVOList = hallPage.getRecords().stream().map(this::convert).collect(Collectors.toList());
        hallVOPage.setRecords(hallVOList);
        return hallVOPage;
    }
}

